/**
 * Created with IntelliJ IDEA.
 * User: osereda
 * Date: 12.06.13
 */
package com.google.code.bankagregator.common;

import com.google.code.bankagregator.adapter.Adapter;
import com.google.code.bankagregator.adapter.exception.AdapterException;
import com.google.code.bankagregator.common.reader.CreditReader;
import com.google.code.bankagregator.common.reader.DepositReader;
import com.google.code.bankagregator.entities.Credit;
import com.google.code.bankagregator.entities.Deposit;
import com.google.code.bankagregator.vo.AdapterResult;
import com.google.code.bankagregator.vo.AdapterWarning;

import java.util.ArrayList;
import java.util.List;

/**
 * Abstract class for adaptor
 */
abstract public class AbstractAdapter implements Adapter {

    /**
     * Call product readers for credits and deposits.
     *
     * @return AdapterResult data.
     */
    @Override
    public AdapterResult getResult() {
        AdapterResult result = new AdapterResult();
        List<Credit> credits = new ArrayList<>();
        List<Deposit> deposits = new ArrayList<>();
        List<AdapterWarning> warnings = new ArrayList<>();

        List<DepositReader> depositSources = getDepositReadersList();
        List<CreditReader> creditSources = getCreditReadersList();

        for (DepositReader source : depositSources) {
            try {
                List<Deposit> product = source.getDeposits();
                deposits.addAll(product);
            } catch (AdapterException e) {
                warnings.add(new AdapterWarning(e.getMessage()));
            } catch (Exception ex) {
                warnings.add(new AdapterWarning(ex.getMessage()));
            }
        }


        for (CreditReader source : creditSources) {
            try {
                List<Credit> product = source.getCredits();
                credits.addAll(product);
            } catch (AdapterException e) {
                warnings.add(new AdapterWarning(e.getMessage()));
            }
        }

        result.setCredits(credits);
        result.setDeposits(deposits);
        result.setWarnings(warnings);

        return result;
    }


    /**
     * Getting list of data sources
     *
     * @return List
     */
    abstract public List<CreditReader> getCreditReadersList();

    /**
     * Getting list of data sources
     *
     * @return List
     */
    abstract public List<DepositReader> getDepositReadersList();


}